package dbops

import (
	"database/sql"
	"fmt"
	"github.com/go-sql-driver/mysql"
	"gitee.com/DengAnbang/Computation/src/config"

	"gitee.com/DengAnbang/goutils/loge"
)

var (
	dbConn *sql.DB
	err    error
)

func init() {
	dataSource := fmt.Sprintf("%s@tcp(%s)", config.ConfigBean.DatabaseUserName+":"+config.ConfigBean.DatabasePassWord, config.ConfigBean.DatabaseAddress+":"+config.ConfigBean.DatabasePort)
	databaseName := config.ConfigBean.DatabaseName
	dataSourceName := fmt.Sprintf("%s/%s?charset=utf8", dataSource, databaseName)
	dbConn, err = sql.Open("mysql", dataSourceName)
	if err != nil {
		goto Err
	}
	err = dbConn.Ping()
	if err == nil {
		goto End
	}
	if v, ok := err.(*mysql.MySQLError); ok && v.Number == 1049 {
		dbConn, err = sql.Open("mysql", dataSource+"/")
		if err != nil {
			goto Err
		}
		err = dbConn.Ping()
		if err != nil {
			goto Err
		}
		_, err = dbConn.Exec(fmt.Sprintf("create database if not exists %s character set utf8;", databaseName))
		if err != nil {
			goto Err
		}
		dbConn, err = sql.Open("mysql", dataSourceName)
		if err != nil {
			goto Err
		}
	}
End:
//数据库连接正常,初始化数据库
	err = initDatabase(dbConn)

Err:
	if err != nil {
		if dbConn != nil {
			dbConn.Close()
		}
		loge.W(err)
		panic(err)
	}

}
func initDatabase(db *sql.DB) error {
	if err = createTable(db); err != nil {
		return err
	}
	if err = updateTable(db); err != nil {
		return err
	}
	return nil
}

func createTable(db *sql.DB) (error) {
	if err = CreateUserTable(db); err != nil {
		return err
	}
	if err = CreateSessionTable(db); err != nil {
		return err
	}
	if err = CreateTreeTable(db); err != nil {
		return err
	}
	if err = CreateUserTreeTable(db); err != nil {
		return err
	}
	if err = CreateTemplateTable(db); err != nil {
		return err
	}
	if err = CreateModelTable(db); err != nil {
		return err
	}
	return nil
}

func updateTable(db *sql.DB) error {
	if err = UpTreeTable(db); err != nil {
		return err
	}
	return nil
}
